async function getCookieString(url) {
  const { session } = require('electron')
  const cookies = await session.defaultSession.cookies.get({ url });
  return cookies.map(c => `${c.name}=${c.value}`).join('; ');
}
async function getCookies(url) {
  const { session } = require('electron')
  const cookies = await session.defaultSession.cookies.get({ url });
  return cookies;
}

async function getInventory() {
  // https://steamcommunity.com/inventory/{steamId}/{appId}/{contextId}?l=schinese&count=75
  const api = 'https://steamcommunity.com/inventory/76561199815367524/730/2?l=schinese&count=75'
  // const params = {
  //   appid: 753,
  //   steamid: 76561199679740669,
  //   contextid: 1,
  //   language: 'zh-CN'
  // }
  const { net } = require('electron')
  const cookieString = await getCookieString(api);
  console.log('cookieString', cookieString);
  const request = net.request({
    url: api,
    method: 'GET',
    headers: {
      'Cookie': cookieString
    }
  })
  // request.write(JSON.stringify(params))

  return new Promise((resolve, reject) => {
    let data = '';
    console.log('request1', request);
    request.on('response', (response) => {
      console.log(`STATUS: ${response.statusCode}`)
      console.log(`HEADERS: ${JSON.stringify(response.headers)}`)

      response.on('data', (chunk) => {
        data += chunk;
      })

      response.on('end', () => {
        try {
          const parsedData = JSON.parse(data);
          resolve(parsedData);
        } catch (error) {
          reject(error);
        }
      })

      response.on('error', (error) => {
        reject(error);
      })
    })

    request.on('error', (error) => {
      console.log('error', error);
      reject(error);
    })

    request.end()
  });
}

async function sendPrice() {
  // https://steamcommunity.com/inventory/{steamId}/{appId}/{contextId}?l=schinese&count=75
  const api = 'https://steamcommunity.com/tradeoffer/new/send'
  // const params = {
  //   appid: 753,
  //   steamid: 76561199679740669,
  //   contextid: 1,
  //   language: 'zh-CN'
  // }
  const { net } = require('electron')
  const cookies = await getCookies(api);
  const cookieString = cookies.map(c => `${c.name}=${c.value}`).join('; ');
  const sessionid = cookies.find(c => c.name === 'sessionid').value;
  console.log('cookieString', cookieString);
  const json_tradeoffer = JSON.stringify({
    "newversion": true,
    "version": 2,
    "me": {
      "assets": [], "currency": [], "ready": false
    }, "them": {
      "assets": [
        { "appid": "730", "contextid": "2", "amount": 1, "assetid": "44428402499" }
      ],
      "currency": [], "ready": false
    }
  });
  // 参数来源： https://steamcommunity.com/tradeoffer/new/?partner=1855101796&token=iG97AduT
  const trade_offer_create_params = JSON.stringify({ "trade_offer_access_token": "iG97AduT" });
  const request = net.request({
    url: api,
    method: 'POST',
    headers: {
      'Cookie': cookieString,
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })

  const params = new URLSearchParams();
  params.append('sessionid', sessionid);
  params.append('serverid', '1');
  params.append('partner', '76561199815367524'); // 接收方
  params.append('captcha', '');
  params.append('json_tradeoffer', json_tradeoffer);
  params.append('trade_offer_create_params', trade_offer_create_params);

  request.write(params.toString());

  return new Promise((resolve, reject) => {
    let data = '';
    console.log('request1', request);
    request.on('response', (response) => {
      console.log(`STATUS: ${response.statusCode}`)
      console.log(`HEADERS: ${JSON.stringify(response.headers)}`)

      response.on('data', (chunk) => {
        data += chunk;
      })

      response.on('end', () => {
        try {
          const parsedData = JSON.parse(data);
          resolve(parsedData);
        } catch (error) {
          reject(error);
        }
      })

      response.on('error', (error) => {
        reject(error);
      })
    })

    request.on('error', (error) => {
      console.log('error', error);
      reject(error);
    })

    request.end()
  });
}

module.exports = {
  getInventory,
  sendPrice
}